package refobjects

import (
	v0 "gitee.com/ymofen/refobjects/v0"
)

type RefWrapper struct {
	Handle any
	Object any
}

type RefFactory interface {
	// 设定创建内部对象的函数
	SetNewObjectFunc(fn func(conf string) (any, error))

	// 设定内部对象的销毁函数
	SetCloseObjectFunc(fn func(obj any) error)

	AcquireRefCount(handle any) (int, error)

	// 取出或新建一个 句柄，引用计数已 +1
	Acquire(conf string) (handle any, object any, err error)

	Release(handle any) error
}

var (
	defaultRefFactory RefFactory = v0.NewRefObjectList()
)

func SetDefaultFactory(f RefFactory) {
	defaultRefFactory = f
}

func (r *RefWrapper) RefCounter() int {
	ret, _ := defaultRefFactory.AcquireRefCount(r.Handle)
	return ret
}

func (r *RefWrapper) Close() error {
	return defaultRefFactory.Release(r.Handle)
}

func Acquire(conf string) (r *RefWrapper, err error) {
	var ret RefWrapper
	r = &ret
	ret.Handle, ret.Object, err = defaultRefFactory.Acquire(conf)
	if err != nil {
		return
	}
	return
}

func SetDefaultNewObjectFunc(fn func(conf string) (any, error)) {
	defaultRefFactory.SetNewObjectFunc(fn)
}
